const api = require('../../utils/api.js')
const pagePermission = require('../../utils/pagepermission.js')

Page({
  data: {
    adminPermissions: [],
    loading: false
  },

  onLoad() {
    // 检查权限 - 只有超级管理员可以查看
    const app = getApp()
    const adminInfo = app ? app.globalData.adminInfo : null
    
    if (!adminInfo || adminInfo.id !== 1) {
      wx.showToast({
        title: '权限不足',
        icon: 'none'
      })
      setTimeout(() => {
        wx.navigateBack()
      }, 1500)
      return
    }
    
    this.loadAdminPermissions()
  },

  onShow() {
    // 再次检查权限
    const app = getApp()
    const adminInfo = app ? app.globalData.adminInfo : null
    
    if (!adminInfo || adminInfo.id !== 1) {
      wx.navigateBack()
      return
    }
    
    this.loadAdminPermissions()
  },

  async loadAdminPermissions() {
    this.setData({ loading: true })

    try {
      const app = getApp()
      const globalData = app ? app.globalData : { token: '', baseUrl: '' }
      
      const res = await new Promise((resolve, reject) => {
        wx.request({
          url: globalData.baseUrl + '/getAllAdminPermissions',
          method: 'GET',
          header: {
            'content-type': 'application/json',
            'Authorization': globalData.token ? 'Bearer ' + globalData.token : ''
          },
          success: (res) => {
            if (res.statusCode === 200) {
              resolve(res.data)
            } else {
              reject(res)
            }
          },
          fail: reject
        })
      })

      if (res.code === 1) {
        this.setData({
          adminPermissions: res.data
        })
      } else {
        wx.showToast({
          title: res.msg || '加载失败',
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('加载管理员权限失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 格式化权限显示
  formatPermissions(permissions) {
    const moduleNames = {
      'product_manage': '产品管理',
      'model_manage': '型号管理',
      'process_manage': '工序管理',
      'price_manage': '价格管理',
      'order_manage': '订单管理',
      'allocation_manage': '分工管理',
      'report_manage': '报工管理',
      'active_report_manage': '主动报工管理',
      'admin_manage': '管理员管理'
    }

    const actionNames = {
      'view': '查看',
      'add': '新增',
      'edit': '编辑',
      'delete': '删除',
      'batch': '批量操作',
      'audit': '审核'
    }

    const formatted = []
    for (const [module, actions] of Object.entries(permissions)) {
      if (Array.isArray(actions) && actions.length > 0) {
        const moduleName = moduleNames[module] || module
        const actionList = actions.map(action => actionNames[action] || action).join('、')
        formatted.push(`${moduleName}: ${actionList}`)
      }
    }

    return formatted.length > 0 ? formatted.join('\n') : '无权限'
  },

  onRefresh() {
    this.loadAdminPermissions()
  }
})

